cc.Class({
    extends: cc.Component,

    properties: {
        MyBase: 
        {
            type: cc.Sprite,
            default: null,
        },
        MyCampList:
        {
            default: [],
            type: [cc.Sprite],
        },
        
        OtherBase:
        {
            type: cc.Sprite,
            default: null,
        },
        OtherCampList:
        {
            default: [],
            type: [cc.Sprite],
        },

        BuildingList:
        {
            default: [],
            type: [cc.Node],
        },

        TowerList:
        {
            default: [],
            type: [cc.Sprite],
        },

        Soilder:
        {
            type: cc.Prefab,
            default: null,
        },

        SoidlerLayout:
        {
            type: cc.Prefab,
            default: null,
        },

        _FirstClickNode:
        {
            default: null,
            type: cc.Node,
        },
        _SecondClickNode:
        {
            default: null,
            type: cc.Node,
        },

        _TowerTargetList:
        {
            default: [],
            type: [cc.Node],
        },

        _SoilderPool:
        {
            default: null,
            type: cc.NodePool,
        },

        _SoilderLayoutPool:
        {
            default: null,
            type: cc.NodePool,
        },

        WinLostLabel:
        {
            default: null,
            type: cc.Label,
        },
    },

    onLoad: function() 
    {
        // let len = cc.pDistance(this.node.position, this.node.position);
        this.WinLostLabel.node.active = false;
        cc.director.getCollisionManager().enabled = true;
        cc.director.getCollisionManager().enabledDebugDraw = true;
        // 我方
        let tmpScript;
        tmpScript = this.MyBase.getComponent("Camp");
        tmpScript.Type = 1;
        tmpScript.Category = 1;
        tmpScript.MaxSoilder = 50;
        for (let index = 0; index < this.MyCampList.length; index++) 
        {
            let element = this.MyCampList[index];
            tmpScript = element.getComponent("Camp");
            tmpScript.Type = 1;
            tmpScript.Category = 2;
            this.BuildingList.push(element);
        }

        // 敌方
        let otherTmpScript;
        otherTmpScript = this.OtherBase.getComponent("Camp");
        otherTmpScript.Category = 1;
        otherTmpScript.Type = 2;
        otherTmpScript.MaxSoilder = 50;
        for (let index = 0; index < this.OtherCampList.length; index++) 
        {
            let element = this.OtherCampList[index];
            otherTmpScript = element.getComponent("Camp");
            otherTmpScript.Type = 2;
            otherTmpScript.Category = 2;
            this.BuildingList.push(element);
        }

        // 塔
        let towerTmpScript;
        for (let index = 0; index < this.TowerList.length; index++) 
        {
            let element = this.TowerList[index];
            towerTmpScript = element.getComponent("Camp");
            towerTmpScript.Type = 3;
            towerTmpScript.Category = 3;
            this.BuildingList.push(element);
        }
        this._SoilderPool = new cc.NodePool();
        for(let i = 0; i < 25; ++i)
        {
            let tmpSoilder = cc.instantiate(this.Soilder);
            this._SoilderPool.put(tmpSoilder);
        }

        this._SoilderLayoutPool = new cc.NodePool();
        for(let i = 0; i < 5; ++i)
        {
            let tmpSoilderLayout = cc.instantiate(this.SoidlerLayout);
            this._SoilderLayoutPool.put(tmpSoilderLayout);
        }
    },

    start: function() 
    {
        this.node.on(cc.Node.EventType.TOUCH_END, function(touch, event) 
        {
            let bTouch = false;
            if(this.MyBase.node.getBoundingBoxToWorld().contains(touch.getLocation())) 
            {
                this.setTouchState(this.MyBase);
                bTouch = true;
            }
            if(this.OtherBase.node.getBoundingBoxToWorld().contains(touch.getLocation()))
            {
                this.setTouchState(this.OtherBase);
                bTouch = true;
            }
            for (let index = 0; index < this.MyCampList.length; index++) 
            {
                let element = this.MyCampList[index];
                if(element.node.getBoundingBoxToWorld().contains(touch.getLocation()))
                {
                    this.setTouchState(element);
                    bTouch = true;
                    break;
                }
            }
            for (let index = 0; index < this.OtherCampList.length; index++) {
                let element = this.OtherCampList[index];
                if(element.node.getBoundingBoxToWorld().contains(touch.getLocation()))
                {
                    this.setTouchState(element);
                    bTouch = true;
                    break;
                }
            }
            for (let index = 0; index < this.TowerList.length; index++) {
                let element = this.TowerList[index];
                if(element.node.getBoundingBoxToWorld().contains(touch.getLocation()))
                {
                    this.setTouchState(element);
                    bTouch = true;
                    break;
                }
            }
            if(bTouch === false)
            {
                this.setTouchState(null);
            }
            
        }, this)
    },

    update: function(dt) 
    {   
        this.AILogic();
        
    },

    onDisable: function() 
    {
        cc.director.getCollisionManager().enabled = false;
        cc.director.getCollisionManager.enabledDebugDraw = false;    
        this.node.off(cc.Node.EventType.TOUCH_END);
    },

    // 士兵和物体碰撞enter
    onSoilderCollisionEnter: function(camp, soilder)
    {
        let campScript = camp.getComponent("Camp")
        let soilderScript = soilder.getComponent("Soilder")
        
        if(campScript.Type === soilderScript.Type)   // 己方
        {
            campScript.changeSoliderNum(1);
        }
        else if(campScript.Type === 3)   // 中立塔
        {
            campScript.changeSoliderNum(1);
            campScript.Type = soilderScript.Type;
        }
        else                            // 敌方
        {
            campScript.changeSoliderNum(-1);
            if(campScript.CurSoilderNum === 0)
            {
                campScript.Type = soilderScript.Type;
            }
        }
        this.removeSoilder(soilder.node);
        this.CheckWinLost();
    },

    // 设置触摸状态
    setTouchState: function(touchNode)
    {
        if(touchNode === null)
        {
            this._FirstClickNode = null;
            this._SecondClickNode = null;
        }
        else
        {
            if(this._FirstClickNode === null)
            {
                let campScript = touchNode.getComponent("Camp")
                if(campScript.Type === 1)
                {
                    this._FirstClickNode = touchNode;
                }
            }
            else
            {
                if(this._FirstClickNode !== touchNode)
                {
                    this._SecondClickNode = touchNode;
                    this.doLogic(this._FirstClickNode, this._SecondClickNode);
                    this._FirstClickNode = null;
                    this._SecondClickNode = null;
                }
            }
        }
    },

    // 执行逻辑
    doLogic: function(fromNode, toNode)
    {
        let fromNodeScript = fromNode.getComponent("Camp");
        let halfNum = Math.ceil(fromNodeScript.CurSoilderNum/2);
        fromNodeScript.changeSoliderNum(-halfNum);
        let theSoilderLayout = this.createSoilderLayout();
        let theSoilderLayoutScript = theSoilderLayout.getComponent("SoilderLayout");
        theSoilderLayoutScript.FromNode = fromNode;
        theSoilderLayoutScript.ToNode = toNode; 
        theSoilderLayoutScript.Type = fromNodeScript.Type;
        theSoilderLayout.parent = this.node;
        theSoilderLayoutScript.init();
        theSoilderLayout.active = true;
        // theSoilderLayout.setPosition(fromNode.node.position);
        for (let i = 0; i < halfNum; i++) 
        {
            let theSoilder = this.createSoilder();
            let theSoilderScript = theSoilder.getComponent("Soilder");
            theSoilderScript.Type = fromNodeScript.Type;
            theSoilderScript.FromNode = fromNode;
            theSoilderScript.ToNode = toNode;
            theSoilder.parent = theSoilderLayout
            // theSoilder.parent = this.node;
            theSoilder.active = true;
        }
    },

    // 创建放士兵的容器
    createSoilderLayout: function()
    {
        let tmpSoilderLayout = null;
        if(this._SoilderLayoutPool.size() > 0)
        {
            tmpSoilderLayout = this._SoilderLayoutPool.get();
        }
        else
        {   
            tmpSoilderLayout = cc.instantiate(this.SoidlerLayout);
        }
        return tmpSoilderLayout;
    },

    // 移除放士兵的容器
    removeSoilderLayout: function(theSoilderLayout)
    {
        theSoilderLayout.active = false;
        this._SoilderLayoutPool.put(theSoilderLayout);
    },

    // 创建士兵
    createSoilder: function()
    {
        let tmpSoilder = null;
        if(this._SoilderPool.size() > 0)
        {
            tmpSoilder = this._SoilderPool.get();
        }
        else
        {   
            tmpSoilder = cc.instantiate(this.Soilder);
        }
        return tmpSoilder;
    },

    // 移除士兵
    removeSoilder: function(theSoilder)
    {
        let bWillRmoveSoilderLayout = false
        let theSoilderParent = null;
        if(theSoilder.parent && theSoilder.parent.childrenCount === 1)
        {
            bWillRmoveSoilderLayout = true;
            theSoilderParent = theSoilder.parent;
        }
        this.removeTowerTarget(theSoilder);
        this._SoilderPool.put(theSoilder);
        if(bWillRmoveSoilderLayout)
        {
            this.removeSoilderLayout(theSoilderParent);
        }
    },

    // 如果士兵在塔的攻击范围，则加入
    addTowerTarget: function(target)
    {
        // this.removeTowerTarget(target);
        this._TowerTargetList.push(target);
    },

    // 如果士兵不在塔的攻击范围或死亡，则移除
    removeTowerTarget: function(target)
    {
        for (let index = 0; index < this._TowerTargetList.length; index++) 
        {
            let element = this._TowerTargetList[index];
            if(element === target)
            {
                this._TowerTargetList.splice(index, 1);
            }
        }
    },

    // 获取塔的范围攻击士兵的数量
    getTowerTargetLength: function()
    {
        return this._TowerTargetList.length; 
    },

    // 攻击士兵
    attackTarget: function()
    {
        // 移除相同阵营的士兵
        for (let index = this._TowerTargetList.length-1; index >= 0; index--) 
        {
            let element = this._TowerTargetList[index];
            let soilderScript = element.getComponent("Soilder");
            let towerScirpt = this.TowerList[0].node.getComponent("Camp");
            if(soilderScript.Type === towerScirpt.Type)
            {
                this.removeTowerTarget(element);
            }
        }

        // 攻击不同阵营的士兵
        // for(let index = 0; index < this._TowerTargetList.length; index++)
        // {
            let element = this._TowerTargetList[0];
            if(element)
            {
                this.removeSoilder(element);
                
            }
        // }
    },

    // 跑AI逻辑
    // 1.基地兵超过40%时，100%派兵至离己方基地最近的非己方兵营、中立塔(等建筑)；
    // 2.当己方兵营、中立塔超过50%时，60%派兵至离己方基地最近的非己方兵营、中立塔(等建筑)，40%概率派兵至己方兵力未满的兵营、中立塔；
    AILogic: function()
    {
        let otherBaseCampScirpt = this.OtherBase.getComponent("Camp");
        if(otherBaseCampScirpt.CurSoilderNum/otherBaseCampScirpt.MaxSoilder > 0.4)
        {
            let nearestBuilding = this.AIFindNearestSelfBuilding(this.OtherBase);
            if(nearestBuilding)
            {
                this.doLogic(this.OtherBase, nearestBuilding);
            }
        }
        for (let index = 0; index < this.BuildingList.length; index++)
        {
            let element = this.BuildingList[index];
            let buildScript = element.getComponent("Camp");
            if(buildScript.Type === 2 && buildScript.CurSoilderNum/buildScript.MaxSoilder > 0.5)
            {
                if(Math.random() >= 0.4)
                {
                    let nearestOtherBuilding = this.AIFindNearestOtherBuilding(element);
                    if(nearestOtherBuilding)
                    {
                        this.doLogic(element, nearestOtherBuilding);
                    }
                }
                else
                {
                    // let nearestBuilding = this.AIFindNearestSelfBuilding(element);
                    // if(nearestBuilding)
                    // {
                        // this.doLogic(element, nearestBuilding);
                    // }
                }
            }    
        }
    },

    // 寻找最近的己方建筑，包括中立塔
    AIFindNearestSelfBuilding(fromNode)
    {
        let minLen = 2000;
        let nearestBuilding = null;
        for (let index = 0; index < this.BuildingList.length; index++) 
        {
            let element = this.BuildingList[index];
            if(fromNode !== element)
            {
                let fromCampScript = fromNode.getComponent("Camp");
                let eleCampScript = element.getComponent("Camp");
                if((fromCampScript.Type === eleCampScript.Type || eleCampScript.Type === 3) && eleCampScript.CurSoilderNum < eleCampScript.MaxSoilder)
                {
                    let dis = fromNode.node.position.sub(element.node.position).mag();
                    if(dis < minLen)
                    {
                        minLen = dis;
                        nearestBuilding = element;
                    }
                }
            }
        }
        return nearestBuilding;
    },

    // 寻找最近的敌方建筑，包括中立塔
    AIFindNearestOtherBuilding(fromNode)
    {
        let minLen = 2000;
        let nearestBuilding = null;
        for (let index = 0; index < this.BuildingList.length; index++) 
        {
            let element = this.BuildingList[index];
            if(fromNode !== element)
            {
                let fromCampScript = fromNode.getComponent("Camp");
                let eleCampScript = element.getComponent("Camp");
                if(fromCampScript.Type !== eleCampScript.Type)
                {
                    let dis = fromNode.node.position.sub(element.node.position).mag();
                    if(dis < minLen)
                    {
                        minLen = dis;
                        nearestBuilding = element;
                    }
                }
            }
        }
        return nearestBuilding;
    },

    // 判断输赢
    CheckWinLost: function()
    {
        let buildingType = 1;
        let bAllType = true;
        for(let index = 0; index < this.BuildingList.length; index++)
        {
            let element = this.BuildingList[index];
            let eleCampScript = element.getComponent("Camp");
            if(index === 0)
            {
                buildingType = eleCampScript.Type;
            }
            else
            {
                if(eleCampScript.Type !== buildingType)
                {
                    bAllType = false;
                    break;
                } 
            }
        }
        if(bAllType)
        {
            this.DoWinLostLogic(buildingType === 1)
        }
    },

    /* 处理输赢逻辑
    param: result 结果
    */ 
    DoWinLostLogic: function(result)
    {
        if(result)
        {
            this.WinLostLabel.string = "你赢了";
        }
        else
        {
            this.WinLostLabel.string = "AI赢了";
        }
        this.WinLostLabel.node.active = true;
    }
});
